﻿namespace WMS6.Web
{
    using NPOI.HPSF;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Globalization;
    using System.IO;
    using System.Net;
    using System.Net.Mail;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Web;
    using System.Web.Caching;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Xml;
    using WMS6.Web.BaseInfoDetailServiceRef;
    using WMS6.Web.BaseInfoServiceRef;
    using WMS6.Web.LoginServiceRef;
    using WMS6.Web.UserControls;

    public class BasePage : Page
    {
        public void AlertMsg(string title, string msg, string type)
        {
            ScriptManager.RegisterStartupScript(this.Page, base.GetType(), "", "<script language='javascript'> $.growlUI('" + title + "','" + msg + "','" + type + "');</script>", false);
        }

        protected void BindData2DDL4UserPermissionWareHouse(DropDownList ddl)
        {
            ddl.DataSource = CommoneMethodServiceClientProxy.GetInstance().GetUserPermissionWareHouse();
            ddl.DataTextField = "WhDbDesc";
            ddl.DataValueField = "WhDbID";
            ddl.DataBind();
            ddl.Items.Remove(new ListItem(this.UserInfo.WhDbDesc, this.UserInfo.CurrentWH));
        }

        protected void BindData2DDL4WareHouse(DropDownList ddl)
        {
            ddl.DataSource = CommoneMethodServiceClientProxy.GetInstance().GetWareHouseDataSource();
            ddl.DataTextField = "WhDbDesc";
            ddl.DataValueField = "WhDbID";
            ddl.DataBind();
            ddl.Items.Remove(new ListItem(this.UserInfo.WhDbDesc, this.UserInfo.CurrentWH));
        }

        protected void BindData2DDLByCartonGroup(DropDownList ddl)
        {
            ddl.DataSource = CommoneMethodServiceClientProxy.GetInstance().GetCartonGroup4Select();
            ddl.DataTextField = "Description";
            ddl.DataValueField = "CartonGroup";
            ddl.DataBind();
        }

        protected void BindData2DDLByCycleCountRule(DropDownList ddl)
        {
            ddl.DataSource = CommoneMethodServiceClientProxy.GetInstance().GetCycleCountRule4Select();
            ddl.DataTextField = "DESCR";
            ddl.DataValueField = "CC_ADJ_RULE_ID";
            ddl.DataBind();
        }

        protected void BindData2DDLByLotTemplate(DropDownList ddl)
        {
            ddl.DataSource = CommoneMethodServiceClientProxy.GetInstance().GetLotTemplate4Select();
            ddl.DataTextField = "Description";
            ddl.DataValueField = "LotTemplateID";
            ddl.DataBind();
        }

        protected void BindData2DDLByPreValue(DropDownList ddl, string preValue)
        {
            List<WMS6.Web.CommonMethodServiceRef.PreferenceValueInfo> preferenceValueInfos = CommoneMethodServiceClientProxy.GetInstance().GetPreferenceValueByID(preValue);
            if ((preferenceValueInfos != null) && (preferenceValueInfos.Count > 0))
            {
                ddl.DataSource = preferenceValueInfos;
                ddl.DataTextField = "Description";
                ddl.DataValueField = "PrefValValue";
                ddl.DataBind();
                for (int i = 0; i < preferenceValueInfos.Count; i++)
                {
                    if (preferenceValueInfos[i].IsDisplayDefault == "Y")
                    {
                        ddl.SelectedValue = preferenceValueInfos[i].PrefValValue;
                        break;
                    }
                }
            }
        }

        protected void BindData2DDLByReceiptValidation(DropDownList ddl)
        {
            ddl.DataSource = CommoneMethodServiceClientProxy.GetInstance().GetReceiptValidation4Select();
            ddl.DataTextField = "Description";
            ddl.DataValueField = "RECEIPTVALIDATIONID";
            ddl.DataBind();
        }

        protected void BindData2DDLByRules(DropDownList ddl, string ruleID)
        {
            ddl.DataSource = CommoneMethodServiceClientProxy.GetInstance().GetRules4Select(ruleID);
            ddl.DataTextField = "Description";
            ddl.DataValueField = "RuleID";
            ddl.DataBind();
        }

        protected void BindData2DDLByRules(DropDownList ddl, string ruleID, bool isFirstEmpty)
        {
            ddl.DataSource = CommoneMethodServiceClientProxy.GetInstance().GetRules4Select(ruleID);
            ddl.DataTextField = "Description";
            ddl.DataValueField = "RuleID";
            ddl.DataBind();
            if (isFirstEmpty)
            {
                ddl.Items.Insert(0, "");
            }
        }

        protected void BindData2DDLBySysCode(List<DropDownList> ddls, string codeType)
        {
            List<WMS6.Web.CommonMethodServiceRef.SysCode4DDL> sysCode4ddl = CommoneMethodServiceClientProxy.GetInstance().GetSysCodeDataSource(codeType);
            foreach (DropDownList ddl in ddls)
            {
                ddl.DataSource = sysCode4ddl;
                ddl.DataTextField = "SysCodeText";
                ddl.DataValueField = "SysCodeValue";
                ddl.DataBind();
            }
        }

        protected void BindData2DDLBySysCode(DropDownList ddl, string codeType)
        {
            try
            {
                int i;
                DataRow[] drs = this.GetSysCodeDetailDataRows(codeType);
                if ((drs == null) || (drs.Length <= 0))
                {
                    return;
                }
                string userLanguage = this.UserInfo.Preference.Lang;
                string descr = "CN_DESCR";
                string CS40001 = userLanguage.ToUpper();
                if (CS40001 != null)
                {
                    if (!(CS40001 == "ZH-CN"))
                    {
                        if (CS40001 == "ZH-TW")
                        {
                            goto Label_007A;
                        }
                        if (CS40001 == "EN-*")
                        {
                            goto Label_0082;
                        }
                    }
                    else
                    {
                        descr = "CN_DESCR";
                    }
                }
                goto Label_008A;
            Label_007A:
                descr = "TW_DESCR";
                goto Label_008A;
            Label_0082:
                descr = "EN_DESCR";
            Label_008A:
                i = 0;
                while (i < drs.Length)
                {
                    ddl.Items.Add(new ListItem(drs[i][descr].ToString(), drs[i]["SYS_CODE"].ToString()));
                    i++;
                }
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
                ddl.DataSource = CommoneMethodServiceClientProxy.GetInstance().GetSysCodeDataSource(codeType);
                ddl.DataTextField = "SysCodeText";
                ddl.DataValueField = "SysCodeValue";
                ddl.DataBind();
            }
        }

        protected void BindData2DDLBySysCode(MultipleSelectControl msc, string codeType)
        {
            if (this.UserInfo != null)
            {
                msc.UserLanguage = this.UserInfo.Preference.Lang;
            }
            else
            {
                msc.UserLanguage = "zh-CN";
            }
            msc.ListItemSource = this.GetSysCodeDetailDataRows(codeType);
        }

        protected void BindData2DDLBySysCode(MultipleSelectControl msc, DropDownList ddl)
        {
            msc.ddlTempDropDownList = ddl;
        }

        protected void BindData2DDLBySysCode(DropDownList ddl, string codeType, bool isFirstEmpty)
        {
            this.BindData2DDLBySysCode(ddl, codeType);
            if (isFirstEmpty)
            {
                ddl.Items.Insert(0, "");
            }
        }

        protected void BindData2DDLBySysCode(MultipleSelectControl msc, string codeType, string defaultSelected)
        {
            msc.DefaultSelected = defaultSelected;
            msc.ListItemSource = this.GetSysCodeDetailDataRows(codeType);
        }

        public void BindData2GridView(GridView gv, DataSet ds)
        {
            if ((ds != null) && (ds.Tables[0].Rows.Count > 0))
            {
                gv.DataSource = ds;
                gv.DataBind();
            }
            else if ((((ds != null) && (ds.Tables.Count == 3)) && (ds.Tables[2] != null)) && (ds.Tables[2].Rows.Count > 0))
            {
                gv.DataSource = ds.Tables[2];
                gv.DataBind();
            }
            else
            {
                if (ds.Tables.Count == 3)
                {
                    ds.Tables[2].Rows.Add(ds.Tables[2].NewRow());
                    gv.ShowFooter = false;
                    gv.DataSource = ds;
                    gv.DataBind();
                    gv.Columns[1].Visible = false;
                }
                else
                {
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                    gv.ShowFooter = false;
                    gv.DataSource = ds;
                    gv.DataBind();
                    gv.Rows[0].Cells[0].Text = "";
                    gv.Columns[1].Visible = false;
                }
                if (gv.Columns[2].Visible && string.IsNullOrEmpty(gv.Columns[2].HeaderText))
                {
                    gv.Columns[2].Visible = false;
                }
            }
        }

        public void BindData2GridView(GridView gv, DataTable dt)
        {
            if ((dt != null) && (dt.Rows.Count > 0))
            {
                gv.DataSource = dt;
                gv.DataBind();
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                gv.ShowFooter = false;
                gv.DataSource = dt;
                gv.DataBind();
                gv.Rows[0].Cells[0].Text = "";
                gv.Columns[1].Visible = false;
                if (gv.Columns[2].Visible && string.IsNullOrEmpty(gv.Columns[2].HeaderText))
                {
                    gv.Columns[2].Visible = false;
                }
            }
        }

        public void BindData2GridView(GridView gv, DataView dv)
        {
            if ((dv != null) && (dv.Count > 0))
            {
                gv.DataSource = dv;
                gv.DataBind();
            }
        }

        public void BindData2GridView(GridView gv, object obj)
        {
            if (obj != null)
            {
                gv.DataSource = obj;
                gv.DataBind();
            }
        }

        public void BindData2GridView1(GridView gv, DataSet ds)
        {
            if ((ds != null) && (ds.Tables[0].Rows.Count > 0))
            {
                gv.Columns[1].Visible = true;
                gv.DataSource = ds;
                gv.DataBind();
            }
            else if ((((ds != null) && (ds.Tables.Count == 3)) && (ds.Tables[2] != null)) && (ds.Tables[2].Rows.Count > 0))
            {
                gv.Columns[1].Visible = true;
                gv.DataSource = ds.Tables[2];
                gv.DataBind();
            }
            else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                gv.ShowFooter = false;
                gv.DataSource = ds;
                gv.DataBind();
                gv.Rows[0].Cells[0].Text = "";
                gv.Columns[1].Visible = false;
                if (gv.Columns[2].Visible && string.IsNullOrEmpty(gv.Columns[2].HeaderText))
                {
                    gv.Columns[2].Visible = false;
                }
            }
        }

        protected void BindDataDDLBySourceFrom(DropDownList ddl, string sourceFrom)
        {
            ddl.DataSource = CommoneMethodService2ClientProxy.GetInstance().GetSysCodeDataSource(sourceFrom);
            ddl.DataTextField = "SysCodeText";
            ddl.DataValueField = "SysCodeValue";
            ddl.DataBind();
        }

        public void BindingOrdersPriority(Image img, Label lab, string priority, string flag)
        {
            if (img != null)
            {
                if (string.IsNullOrEmpty(flag))
                {
                    flag = "0";
                }
                if (!(flag == "1"))
                {
                    img.Visible = false;
                    lab.Text = priority;
                    return;
                }
                lab.Visible = false;
                img.ToolTip = priority;
                string CS40001 = priority;
                if (CS40001 == null)
                {
                    goto Label_00DC;
                }
                if (!(CS40001 == "1"))
                {
                    if (CS40001 == "2")
                    {
                        img.ImageUrl = "../Images/OP02.gif";
                        return;
                    }
                    if (CS40001 == "3")
                    {
                        img.ImageUrl = "../Images/OP03.gif";
                        return;
                    }
                    if (CS40001 == "4")
                    {
                        img.ImageUrl = "../Images/OP04.gif";
                        return;
                    }
                    if (CS40001 == "5")
                    {
                        img.ImageUrl = "../Images/OP05.gif";
                        return;
                    }
                    goto Label_00DC;
                }
                img.ImageUrl = "../Images/OP01.gif";
            }
            return;
        Label_00DC:
            img.ImageUrl = "../Images/OP05.gif";
        }

        protected void BindUomList2DDL(DropDownList ddl, List<WMS6.Web.CommonMethodServiceRef.UomList> uomList)
        {
            if ((uomList != null) && (uomList.Count > 0))
            {
                ddl.DataSource = uomList;
                ddl.DataTextField = "UomDescr";
                ddl.DataValueField = "UomID";
                ddl.DataBind();
            }
            else
            {
                ddl.Items.Clear();
            }
        }

        protected void BindUomList2DDL(DropDownList ddl, string packID)
        {
            if (!string.IsNullOrEmpty(packID))
            {
                List<WMS6.Web.CommonMethodServiceRef.UomList> uomList = CommoneMethodServiceClientProxy.GetInstance().GetUomListByPackID(packID);
                if ((uomList != null) && (uomList.Count > 0))
                {
                    ddl.DataSource = uomList;
                    ddl.DataTextField = "UomDescr";
                    ddl.DataValueField = "UomID";
                    ddl.DataBind();
                }
                else
                {
                    ddl.Items.Clear();
                }
            }
            else
            {
                ddl.Items.Clear();
            }
        }

        public string ChangeDateType(string p)
        {
            if (((p.Substring(0, 4).IndexOf("-") > 0) || (p.Substring(0, 4).IndexOf("/") > 0)) || (p.Substring(0, 4).IndexOf(".") > 0))
            {
                string[] str = p.Split(new char[] { ' ' });
                string CS40003 = this.UserInfo.Preference.DateFormat;
                if (CS40003 != null)
                {
                    if (!(CS40003 == "dd-MM-yyyy"))
                    {
                        if (CS40003 == "dd/MM/yyyy")
                        {
                            string[] str2 = str[0].Split(new char[] { '/' });
                            str[0] = str2[2] + "/" + str2[1] + "/" + str2[0];
                        }
                        else if (CS40003 == "dd.MM.yyyy")
                        {
                            string[] str3 = str[0].Split(new char[] { '.' });
                            str[0] = str3[2] + "." + str3[1] + "." + str3[0];
                        }
                    }
                    else
                    {
                        string[] str1 = str[0].Split(new char[] { '-' });
                        str[0] = str1[2] + "-" + str1[1] + "-" + str1[0];
                    }
                }
                if (!((str.Length <= 1) || string.IsNullOrEmpty(str[1])))
                {
                    p = str[0] + " " + str[1];
                    return p;
                }
                p = str[0];
            }
            return p;
        }

        protected string ChangeLangeugePattern(string pattern)
        {
            switch (pattern.ToLower())
            {
                case "zh-ch":
                    return "zh";

                case "en-us":
                    return "en";

                case "en-*":
                    return "en";
            }
            return "zh";
        }

        protected string ChangeStylePattern(string pattern)
        {
            switch (pattern)
            {
                case "Orange":
                    return "7";

                case "ClassicBlue":
                    return "2";

                case "Black":
                    return "3";

                case "Green":
                    return "4";

                case "LightBlue":
                    return "5";

                case "Purple":
                    return "6";

                case "FashionBlue":
                    return "8";
            }
            return "2";
        }

        public void CreateInitGridviewSQL(string functionID, GridView gv)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendFormat("--初始化 FunctionID:{0} Gridview:{1}", functionID, gv.ID);
            strSql.AppendLine();
            strSql.AppendFormat("DELETE FROM sysadm.CUST_GRIDVIEW WHERE FUNCTION_ID = '{0}' AND GIRDVIEW_ID='{1}'", functionID, gv.ID);
            strSql.AppendLine();
            strSql.AppendFormat("DELETE FROM sysadm.INIT_GRIDVIEW WHERE FUNCTION_ID = '{0}'  AND GRIDVIEW_ID='{1}'", functionID, gv.ID);
            strSql.AppendLine();
            for (int i = 0; i < gv.Columns.Count; i++)
            {
                strSql.AppendFormat("INSERT INTO sysadm.INIT_GRIDVIEW(FUNCTION_ID,GRIDVIEW_ID,COLUMN_INDEX,HEADER_TEXT,FOOTER_TEXT,DATA_FIELD,CSS_CLASS,WIDTH,PAGE_SIZE,CREATED_BY,CREATED_DATE,UPDATED_BY,UPDATED_DATE) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','DBA',GETDATE(),'DBA',GETDATE()) ", new object[] { functionID, gv.ID, i.ToString(), gv.Columns[i].HeaderText, gv.Columns[i].FooterText, gv.Columns[i].SortExpression, gv.Columns[i].ItemStyle.CssClass, this.GetWidthByCssClass(gv.Columns[i].ItemStyle.CssClass), gv.PageSize });
                strSql.AppendLine();
            }
            strSql.AppendLine();
            try
            {
                if (!Directory.Exists("D:/InitGridview"))
                {
                    Directory.CreateDirectory("D:/InitGridview");
                }
                System.IO.File.WriteAllText("D:/InitGridview/" + functionID + "_" + gv.ID + ".sql", strSql.ToString(), Encoding.UTF8);
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
        }

        protected void Export1Excel(string fileName, GridView gv)
        {
            if (gv.Rows.Count > 0)
            {
                if (this.GetValueFromAppSettings("ExcelExport") == "1")
                {
                    base.Response.Clear();
                    base.Response.Buffer = true;
                    base.Response.Charset = "UTF-8";
                    base.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString());
                    base.Response.ContentEncoding = Encoding.UTF8;
                    base.Response.ContentType = "application/ms-excel";
                    base.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
                    StringWriter sWriter = new StringWriter();
                    HtmlTextWriter htmlWriter = new HtmlTextWriter(sWriter);
                    gv.RenderControl(htmlWriter);
                    base.Response.Output.Write(sWriter.ToString());
                    base.Response.Flush();
                    base.Response.End();
                    base.Response.Close();
                }
                else
                {
                    string filename = HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString();
                    base.Response.ContentType = "application/vnd.ms-excel";
                    base.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString()));
                    base.Response.Clear();
                    HSSFWorkbook hssfworkbook = new HSSFWorkbook();
                    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                    dsi.Company = "QuantumAsia";
                    hssfworkbook.DocumentSummaryInformation = dsi;
                    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                    si.Subject = "Export Data To Excel";
                    hssfworkbook.SummaryInformation = si;
                    Sheet sheet1 = this.GetExportSheet(hssfworkbook, gv);
                    MemoryStream file = new MemoryStream();
                    hssfworkbook.Write(file);
                    base.Response.BinaryWrite(file.GetBuffer());
                    base.Response.End();
                }
            }
        }

        protected void Export2Excel(string fileName, GridView gv)
        {
            if (gv.Rows.Count > 0)
            {
                if (this.GetValueFromAppSettings("ExcelExport") == "1")
                {
                    gv.Columns[1].Visible = false;
                    base.Response.Clear();
                    base.Response.Buffer = true;
                    base.Response.Charset = "UTF-8";
                    base.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString());
                    base.Response.ContentEncoding = Encoding.UTF8;
                    base.Response.ContentType = "application/ms-excel";
                    base.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
                    StringWriter sWriter = new StringWriter();
                    HtmlTextWriter htmlWriter = new HtmlTextWriter(sWriter);
                    gv.RenderControl(htmlWriter);
                    string result = Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(sWriter.ToString().Replace("scope=\"col\"", ""), "onmouseout=\"?[^\"]+\"", ""), "onmouseover=\"?[^\"]+\"", ""), "style=\"?[^\"]+\"", ""), "class=\"?[^\"]+\"", ""), "id=\"?[^\"]+\"", ""), "ondblclick=\"?[^\"]+\"", "").Replace("\t", "").Replace("    ", "");
                    base.Response.Output.Write(result);
                    base.Response.Flush();
                    base.Response.End();
                    base.Response.Close();
                }
                else
                {
                    gv.Columns[1].Visible = false;
                    string filename = HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString();
                    base.Response.ContentType = "application/vnd.ms-excel";
                    base.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString()));
                    base.Response.Clear();
                    HSSFWorkbook hssfworkbook = new HSSFWorkbook();
                    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                    dsi.Company = "QuantumAsia";
                    hssfworkbook.DocumentSummaryInformation = dsi;
                    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                    si.Subject = "Export Data To Excel";
                    hssfworkbook.SummaryInformation = si;
                    Sheet sheet1 = this.GetExportSheet(hssfworkbook, gv);
                    MemoryStream file = new MemoryStream();
                    hssfworkbook.Write(file);
                    base.Response.BinaryWrite(file.GetBuffer());
                    base.Response.End();
                }
            }
        }

        protected void Export2Excel(string fileName, string functionID, GridView gridview, DataSet dsData)
        {
            DataSet dsConfig = CommoneMethodServiceClientProxy.GetInstance().GetShowGridviewInfo(functionID, gridview.ID);
            if (((dsConfig != null) && (dsConfig.Tables.Count > 0)) && (dsConfig.Tables[0].Rows.Count > 0))
            {
                MemoryStream ms = new MemoryStream();
                HSSFWorkbook workbook = new HSSFWorkbook();
                HSSFSheet sheet = workbook.CreateSheet("Sheet1") as HSSFSheet;
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "Qt-Asia";
                workbook.DocumentSummaryInformation = dsi;
                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Author = "Qt-Asia";
                si.ApplicationName = "Power WMS6";
                si.LastAuthor = "Qt-Asia";
                si.CreateDateTime = new DateTime?(DateTime.Now);
                workbook.SummaryInformation = si;
                HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow;
                HSSFCellStyle cellDateStyle = workbook.CreateCellStyle() as HSSFCellStyle;
                HSSFDataFormat cellDateFormat = workbook.CreateDataFormat() as HSSFDataFormat;
                if (this.UserInfo.Preference.Time == "Y")
                {
                    cellDateStyle.DataFormat = cellDateFormat.GetFormat("yyyy-MM-dd HH:mm");
                }
                else
                {
                    cellDateStyle.DataFormat = cellDateFormat.GetFormat("yyyy-MM-dd");
                }
                HSSFCellStyle cellNumStyle = workbook.CreateCellStyle() as HSSFCellStyle;
                HSSFDataFormat cellNumFormat = workbook.CreateDataFormat() as HSSFDataFormat;
                string formatValue = this.UserInfo.Preference.Digits_No;
                string formatStr = string.Empty;
                switch (formatValue)
                {
                    case "0":
                        formatStr = "0";
                        break;

                    case "1":
                        formatStr = "0.0";
                        break;

                    case "2":
                        formatStr = "0.00";
                        break;

                    case "3":
                        formatStr = "0.000";
                        break;

                    case "4":
                        formatStr = "0.0000";
                        break;

                    case "5":
                        formatStr = "0.00000";
                        break;

                    default:
                        formatStr = "{0:0}";
                        break;
                }
                if ((formatStr == "0") || (formatStr == "0.00"))
                {
                    cellNumStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat(formatStr);
                }
                else
                {
                    cellNumStyle.DataFormat = cellNumFormat.GetFormat(formatStr);
                }
                try
                {
                    int i = 0;
                    while (i < dsConfig.Tables[0].Rows.Count)
                    {
                        headerRow.CreateCell(i).SetCellValue(dsConfig.Tables[0].Rows[i]["HEADER_TEXT"].ToString());
                        i++;
                    }
                    int rowIndex = 1;
                    string export2ExcelIsSkuString = this.GetValueFromAppSettings("EXPORT_EXCEL_IS_SKU_AS_STRING").ToUpper();
                    for (int rowNo = 0; rowNo < dsData.Tables[0].Rows.Count; rowNo++)
                    {
                        HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
                        HSSFCell cell = null;
                        DataRow row = dsData.Tables[0].Rows[rowNo];
                        for (i = 0; i < dsConfig.Tables[0].Rows.Count; i++)
                        {
                            DateTime datevalue;
                            string columnName = dsConfig.Tables[0].Rows[i]["DATA_FIELD"].ToString();
                            if (columnName.IndexOf('.') >= 0)
                            {
                                columnName = columnName.Substring(columnName.IndexOf('.') + 1);
                            }
                            DataColumn column = dsData.Tables[0].Columns[columnName];
                            cell = dataRow.CreateCell(i) as HSSFCell;
                            string value = row[column].ToString();
                            switch (column.DataType.ToString())
                            {
                                case "System.String":
                                    if (((column.ColumnName.ToUpper() != "SKU_ID") && (column.ColumnName.ToUpper() != "SKU")) && !(column.ColumnName.ToUpper() == "SKUID"))
                                    {
                                        goto Label_0588;
                                    }
                                    if (!(export2ExcelIsSkuString == "Y"))
                                    {
                                        break;
                                    }
                                    cell.SetCellValue(value);
                                    goto Label_0709;

                                case "System.DateTime":
                                    if (!string.IsNullOrEmpty(value))
                                    {
                                        goto Label_05BA;
                                    }
                                    cell.SetCellValue("");
                                    goto Label_0709;

                                case "System.Boolean":
                                {
                                    bool boolvalue = false;
                                    bool.TryParse(value, out boolvalue);
                                    cell.SetCellValue(boolvalue);
                                    goto Label_0709;
                                }
                                case "System.Int16":
                                {
                                    short int16 = 0;
                                    short.TryParse(value, out int16);
                                    cell.SetCellValue((double) int16);
                                    goto Label_0709;
                                }
                                case "System.Int32":
                                {
                                    int int32 = 0;
                                    int.TryParse(value, out int32);
                                    cell.SetCellValue((double) int32);
                                    goto Label_0709;
                                }
                                case "System.Int64":
                                {
                                    long int64 = 0;
                                    long.TryParse(value, out int64);
                                    cell.SetCellValue((double) int64);
                                    goto Label_0709;
                                }
                                case "System.Byte":
                                {
                                    int intV = 0;
                                    int.TryParse(value, out intV);
                                    cell.SetCellValue((double) intV);
                                    goto Label_0709;
                                }
                                case "System.Decimal":
                                {
                                    double decV = 0.0;
                                    double.TryParse(value, out decV);
                                    cell.SetCellValue(decV);
                                    cell.CellStyle = cellNumStyle;
                                    goto Label_0709;
                                }
                                case "System.Single":
                                {
                                    float floatV = 0f;
                                    float.TryParse(value, out floatV);
                                    cell.SetCellValue((double) floatV);
                                    cell.CellStyle = cellNumStyle;
                                    goto Label_0709;
                                }
                                case "System.Double":
                                {
                                    double doubV = 0.0;
                                    double.TryParse(value, out doubV);
                                    cell.SetCellValue(doubV);
                                    cell.CellStyle = cellNumStyle;
                                    goto Label_0709;
                                }
                                case "System.DBNull":
                                    cell.SetCellValue("");
                                    goto Label_0709;

                                default:
                                    cell.SetCellValue(value);
                                    goto Label_0709;
                            }
                            int intSku = 0;
                            if (int.TryParse(value, out intSku))
                            {
                                cell.SetCellValue((double) intSku);
                            }
                            else
                            {
                                cell.SetCellValue(value);
                            }
                            goto Label_0709;
                        Label_0588:
                            cell.SetCellValue(value);
                            goto Label_0709;
                        Label_05BA:
                            DateTime.TryParse(value, out datevalue);
                            cell.SetCellValue(datevalue);
                            cell.CellStyle = cellDateStyle;
                        Label_0709:
                            if (rowNo == (dsData.Tables[0].Rows.Count - 1))
                            {
                                sheet.AutoSizeColumn(i);
                            }
                        }
                        rowIndex++;
                    }
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
                    HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                    HttpContext.Current.Response.End();
                }
                finally
                {
                    ms.Close();
                    headerRow = null;
                    sheet = null;
                    workbook = null;
                    ms = null;
                }
            }
        }

        protected string FormatUrl(string url, string para)
        {
            return string.Format(url, base.Server.UrlEncode(para));
        }

        protected string FormatUrl(string url, string para1, string para2)
        {
            return string.Format(url, base.Server.UrlEncode(para1), base.Server.UrlEncode(para2));
        }

        protected string FormatUrl(string url, string para1, string para2, string para3)
        {
            return string.Format(url, base.Server.UrlEncode(para1), base.Server.UrlEncode(para2), base.Server.UrlEncode(para3));
        }

        protected string FormatUrl(string url, string para1, string para2, string para3, string para4)
        {
            return string.Format(url, new object[] { base.Server.UrlEncode(para1), base.Server.UrlEncode(para2), base.Server.UrlEncode(para3), base.Server.UrlEncode(para4) });
        }

        protected string FormatUrl(string url, string para1, string para2, string para3, string para4, string para5)
        {
            return string.Format(url, new object[] { base.Server.UrlEncode(para1), base.Server.UrlEncode(para2), base.Server.UrlEncode(para3), base.Server.UrlEncode(para4), base.Server.UrlEncode(para5) });
        }

        protected Sheet GetExportSheet(HSSFWorkbook hssfworkbook, GridView gv)
        {
            bool autoSizeColumn = this.GetValueFromAppSettings("ExcelAutoSizeColumn") == "1";
            Sheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
            StringWriter sWriter = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(sWriter);
            gv.RenderControl(writer);
            string renderResult = ("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + writer.InnerWriter.ToString()).Replace("&nbsp;", "").Replace("&", "&amp;").Replace("'", "&apos;");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(renderResult);
            XmlNodeList nodes = doc.SelectSingleNode("div").SelectSingleNode("table").ChildNodes;
            for (int i = 0; i < nodes.Count; i++)
            {
                Row excelRow = sheet1.CreateRow(i);
                for (int j = 0; j < nodes[i].ChildNodes.Count; j++)
                {
                    excelRow.CreateCell(j).SetCellValue(nodes[i].ChildNodes[j].InnerText);
                    if ((i == (nodes.Count - 1)) && autoSizeColumn)
                    {
                        sheet1.AutoSizeColumn(j);
                    }
                }
            }
            return sheet1;
        }

        public string GetFormatDigitString()
        {
            string formatValue = this.UserInfo.Preference.Digits_No;
            switch (formatValue)
            {
                case "0":
                    return "{0:0}";

                case "1":
                    return "{0:0.0}";

                case "2":
                    return "{0:0.00}";

                case "3":
                    return "{0:0.000}";

                case "4":
                    return "{0:0.0000}";

                case "5":
                    return "{0:0.00000}";
            }
            return "{0:0}";
        }

        protected string GetGlobalMsgResource(string code)
        {
            string className = "MsgResource";
            return base.GetGlobalResourceObject(className, code).ToString();
        }

        protected string GetGlobalMsgResource(string code, List<string> paramaters)
        {
            string className = "MsgResource";
            if ((paramaters != null) && (paramaters.Count > 0))
            {
                code = string.Format(base.GetGlobalResourceObject(className, code).ToString(), (object[]) paramaters.ToArray());
                return code;
            }
            code = base.GetGlobalResourceObject(className, code).ToString();
            return code;
        }

        public void GetPageControlXmlElementValue(Page page)
        {
            string xmlpath;
            XmlDocument doc;
            XmlNodeList nodes;
            string strControlName;
            bool bolEnable;
            string strSubControl;
            Exception ex;
            string CS40002;
            if (this.UserInfo.IsGlobal == "N")
            {
                try
                {
                    xmlpath = base.Server.MapPath("../PageConfig/" + page.Title + ".xml");
                    if (System.IO.File.Exists(xmlpath))
                    {
                        doc = new XmlDocument();
                        doc.Load(xmlpath);
                        nodes = doc.SelectSingleNode("PageConfig").ChildNodes;
                        foreach (XmlElement node in nodes)
                        {
                            if (!(node.Name == "PageControl"))
                            {
                                goto Label_0277;
                            }
                            strControlName = node.Attributes["ControlName"].Value;
                            bolEnable = bool.Parse(node.Attributes["Enable"].Value);
                            strSubControl = node.Attributes["SubControl"].Value;
                            if (bolEnable || (page.FindControl(strControlName) == null))
                            {
                                goto Label_0277;
                            }
                            CS40002 = page.FindControl(strControlName).GetType().Name.ToString();
                            if (CS40002 != null)
                            {
                                if (!(CS40002 == "TextBox"))
                                {
                                    if (CS40002 == "DropDownList")
                                    {
                                        goto Label_01A0;
                                    }
                                    if (CS40002 == "CheckBox")
                                    {
                                        goto Label_01BA;
                                    }
                                    if (CS40002 == "Button")
                                    {
                                        goto Label_01D1;
                                    }
                                    if (CS40002 == "LinkButton")
                                    {
                                        goto Label_01E8;
                                    }
                                }
                                else
                                {
                                    ((TextBox) page.FindControl(strControlName)).Enabled = bolEnable;
                                }
                            }
                            goto Label_023A;
                        Label_01A0:
                            ((DropDownList) page.FindControl(strControlName)).Enabled = bolEnable;
                            goto Label_023A;
                        Label_01BA:
                            ((CheckBox) page.FindControl(strControlName)).Enabled = bolEnable;
                            goto Label_023A;
                        Label_01D1:
                            ((Button) page.FindControl(strControlName)).Enabled = bolEnable;
                            goto Label_023A;
                        Label_01E8:
                            if (page.FindControl("td" + strControlName) != null)
                            {
                                page.FindControl("td" + strControlName).Visible = bolEnable;
                            }
                            else
                            {
                                ((LinkButton) page.FindControl(strControlName)).Enabled = bolEnable;
                            }
                        Label_023A:
                            if (!string.IsNullOrEmpty(strSubControl) && (page.FindControl(strSubControl) != null))
                            {
                                ((HtmlImage) page.FindControl(strSubControl)).Disabled = !bolEnable;
                            }
                        Label_0277:;
                        }
                    }
                }
                catch (Exception exception1)
                {
                    ex = exception1;
                    SysLog.GetInstance().LogError(ex);
                }
            }
            else
            {
                try
                {
                    xmlpath = base.Server.MapPath("../PageConfig/Un" + page.Title + ".xml");
                    if (System.IO.File.Exists(xmlpath))
                    {
                        doc = new XmlDocument();
                        doc.Load(xmlpath);
                        nodes = doc.SelectSingleNode("PageConfig").ChildNodes;
                        foreach (XmlElement node in nodes)
                        {
                            if (!(node.Name == "PageControl"))
                            {
                                goto Label_0518;
                            }
                            strControlName = node.Attributes["ControlName"].Value;
                            bolEnable = bool.Parse(node.Attributes["Enable"].Value);
                            strSubControl = node.Attributes["SubControl"].Value;
                            string strValue = node.Attributes["VALUE"].Value;
                            if (bolEnable || (page.FindControl(strControlName) == null))
                            {
                                goto Label_0518;
                            }
                            CS40002 = page.FindControl(strControlName).GetType().Name.ToString();
                            if (CS40002 != null)
                            {
                                if (!(CS40002 == "TextBox"))
                                {
                                    if (CS40002 == "DropDownList")
                                    {
                                        goto Label_047F;
                                    }
                                    if (CS40002 == "CheckBox")
                                    {
                                        goto Label_0496;
                                    }
                                    if (CS40002 == "Button")
                                    {
                                        goto Label_04AD;
                                    }
                                    if (CS40002 == "LinkButton")
                                    {
                                        goto Label_04C4;
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(strValue))
                                    {
                                        ((TextBox) page.FindControl(strControlName)).Text = strValue;
                                    }
                                    ((TextBox) page.FindControl(strControlName)).Enabled = bolEnable;
                                }
                            }
                            goto Label_04DB;
                        Label_047F:
                            ((DropDownList) page.FindControl(strControlName)).Enabled = bolEnable;
                            goto Label_04DB;
                        Label_0496:
                            ((CheckBox) page.FindControl(strControlName)).Enabled = bolEnable;
                            goto Label_04DB;
                        Label_04AD:
                            ((Button) page.FindControl(strControlName)).Enabled = bolEnable;
                            goto Label_04DB;
                        Label_04C4:
                            ((LinkButton) page.FindControl(strControlName)).Enabled = bolEnable;
                        Label_04DB:
                            if (!string.IsNullOrEmpty(strSubControl) && (page.FindControl(strSubControl) != null))
                            {
                                ((HtmlImage) page.FindControl(strSubControl)).Disabled = !bolEnable;
                            }
                        Label_0518:;
                        }
                    }
                }
                catch (Exception exception2)
                {
                    ex = exception2;
                    SysLog.GetInstance().LogError(ex);
                }
            }
        }

        public string GetParamsDateTime()
        {
            return "";
        }

        public string GetParamsEqual()
        {
            return "";
        }

        public string GetParamsString(string p1, string oper)
        {
            int i;
            string str = " ";
            p1 = p1.Replace("'", "''");
            switch (oper)
            {
                case "Begins With":
                    return (str + " LIKE '" + p1 + "%'");

                case "Ends With":
                    return (str + " LIKE '%" + p1 + "'");

                case "One Of":
                {
                    str = str + " IN ( ";
                    string[] array1 = p1.Split(new char[] { ',', ';', '!', ' ' });
                    for (i = 0; i < array1.Length; i++)
                    {
                        if (i == 0)
                        {
                            str = str + "'" + array1[i].ToString() + "'";
                        }
                        else
                        {
                            str = str + " , '" + array1[i].ToString() + "'";
                        }
                    }
                    return (str + " )");
                }
                case "Not One Of":
                {
                    str = str + " NOT IN ( ";
                    string[] array2 = p1.Split(new char[] { ',', ';', '!', ' ' });
                    for (i = 0; i < array2.Length; i++)
                    {
                        if (i == 0)
                        {
                            str = str + "'" + array2[i].ToString() + "'";
                        }
                        else
                        {
                            str = str + " , '" + array2[i].ToString() + "'";
                        }
                    }
                    return (str + " )");
                }
                case "Contains":
                    return (str + " LIKE '%" + p1 + "%'");

                case "Not Contains":
                    return (str + " NOT LIKE '%" + p1 + "%'");

                case "Same As":
                    return (str + " = '" + p1 + "'");

                case "Not Same As":
                    return (str + " != '" + p1 + "'");
            }
            return str;
        }

        public string GetParamsString(string p1, string oper, string p2)
        {
            if (!string.IsNullOrEmpty(p1))
            {
                p1 = this.ChangeDateType(p1);
            }
            if (!string.IsNullOrEmpty(p2))
            {
                p2 = this.ChangeDateType(p2);
            }
            string str = "";
            try
            {
                if (string.IsNullOrEmpty(p1))
                {
                    return str;
                }
                p1 = p1.Replace("'", "''");
                string CS40002 = oper;
                if (CS40002 == null)
                {
                    return str;
                }
                if (!(CS40002 == "Same As"))
                {
                    if (CS40002 != "Before")
                    {
                        if (CS40002 == "After")
                        {
                            return (str + " >= '" + DateTime.Parse(p1).ToShortDateString() + " 00:00:00'");
                        }
                        if (CS40002 == "Between")
                        {
                            goto Label_0117;
                        }
                        if (CS40002 == "Is Null")
                        {
                            return (str + "  IS NULL ");
                        }
                        if (CS40002 != "Not Null")
                        {
                            return str;
                        }
                        goto Label_01B1;
                    }
                }
                else
                {
                    return (str + " = '" + p1 + "'");
                }
                return (str + " <= '" + DateTime.Parse(p1).ToShortDateString() + " 23:59:59'");
            Label_0117:
                if (!string.IsNullOrEmpty(p2))
                {
                    string CS00004 = str;
                    return (CS00004 + " BETWEEN '" + DateTime.Parse(p1).ToShortDateString() + " 00:00:00' AND '" + DateTime.Parse(p2).ToShortDateString() + " 23:59:59'");
                }
                return (str + " >= '" + DateTime.Parse(p1).ToShortDateString() + "' ");
            Label_01B1:
                str = str + " IS NOT NULL ";
            }
            catch
            {
            }
            return str;
        }

        public string GetParamsString(string p1, string oper, string p2, string param)
        {
            if (!string.IsNullOrEmpty(p1))
            {
                p1 = this.ChangeDateType(p1);
            }
            if (!string.IsNullOrEmpty(p2))
            {
                p2 = this.ChangeDateType(p2);
            }
            string str = "";
            param = "@" + param + "@";
            try
            {
                string CS00003;
                if (string.IsNullOrEmpty(p1))
                {
                    return str;
                }
                p1 = p1.Replace("'", "''");
                string CS40002 = oper;
                if (CS40002 == null)
                {
                    return str;
                }
                if (!(CS40002 == "Same As"))
                {
                    if (CS40002 != "Before")
                    {
                        if (CS40002 == "After")
                        {
                            goto Label_0252;
                        }
                        if (CS40002 == "Between")
                        {
                            goto Label_02AA;
                        }
                        if (CS40002 == "Is Null")
                        {
                            return (str + " " + param + " IS NULL ");
                        }
                        if (CS40002 != "Not Null")
                        {
                            return str;
                        }
                        goto Label_03AD;
                    }
                }
                else
                {
                    if ((this.UserInfo.Preference.Time == "N") || (p1.Trim().Length == 10))
                    {
                        CS00003 = str;
                        return (CS00003 + " " + param + " >= '" + DateTime.Parse(p1).ToString() + "' AND " + param + " <= '" + DateTime.Parse(p1).ToString().Replace("0:00:00", "23:59:59") + "' ");
                    }
                    CS00003 = str;
                    return (CS00003 + " " + param + " = '" + DateTime.Parse(p1).ToString() + "' ");
                }
                CS00003 = str;
                return (CS00003 + " " + param + " <= '" + DateTime.Parse(p1).ToString() + "' ");
            Label_0252:
                CS00003 = str;
                return (CS00003 + " " + param + " >= '" + DateTime.Parse(p1).ToString() + "' ");
            Label_02AA:
                if (!string.IsNullOrEmpty(p2))
                {
                    CS00003 = str;
                    return (CS00003 + " " + param + " >= '" + DateTime.Parse(p1).ToString() + "' AND " + param + " <= '" + DateTime.Parse(p2).ToString() + "' ");
                }
                CS00003 = str;
                return (CS00003 + " " + param + " >= '" + DateTime.Parse(p1).ToString() + "' ");
            Label_03AD:
                str = str + " " + param + " IS NOT NULL ";
            }
            catch
            {
            }
            return str;
        }

        protected string GetPreferenceDigit(decimal digit)
        {
            string number = string.Empty;
            try
            {
                number = string.Format(this.GetFormatDigitString(), digit);
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
            return number;
        }

        protected string GetPreferenceDigit(double digit)
        {
            string number = string.Empty;
            try
            {
                number = string.Format(this.GetFormatDigitString(), digit);
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
            return number;
        }

        protected string GetPreferenceDigit(int digit)
        {
            string number = string.Empty;
            try
            {
                number = string.Format(this.GetFormatDigitString(), digit);
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
            return number;
        }

        protected string GetPreferenceDigit(float digit)
        {
            string number = string.Empty;
            try
            {
                number = string.Format(this.GetFormatDigitString(), digit);
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
            return number;
        }

        protected string GetPreferenceDigit(string digit)
        {
            string number = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(digit))
                {
                    string formatStr = this.GetFormatDigitString();
                    decimal dig = decimal.Parse(digit);
                    number = string.Format(formatStr, dig);
                }
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
            return number;
        }

        protected string GetPreferenceFormatString(string formatType)
        {
            string formatValue = string.Empty;
            string CS40001 = formatType.ToUpper();
            if (CS40001 == null)
            {
                return formatValue;
            }
            if (!(CS40001 == "TIME_FORMAT"))
            {
                if (CS40001 != "DATE_FORMAT")
                {
                    return formatValue;
                }
            }
            else
            {
                return this.UserInfo.Preference.Time_Format;
            }
            return this.UserInfo.Preference.DateFormat;
        }

        protected string GetPreferenceLongDate(DateTime dateTime)
        {
            string date = string.Empty;
            try
            {
                if (dateTime != new DateTime())
                {
                    string formatStr = this.GetPreferenceFormatString("DATE_FORMAT") + " " + this.GetPreferenceFormatString("TIME_FORMAT");
                    date = dateTime.ToString(formatStr, DateTimeFormatInfo.InvariantInfo);
                }
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
            return date;
        }

        protected string GetPreferenceLongDate(string dateTime)
        {
            string date = string.Empty;
            try
            {
                DateTime tempDate = DateTime.Parse(dateTime);
                if (tempDate != new DateTime())
                {
                    string formatStr = this.GetPreferenceFormatString("DATE_FORMAT") + " " + this.GetPreferenceFormatString("TIME_FORMAT");
                    date = tempDate.ToString(formatStr, DateTimeFormatInfo.InvariantInfo);
                }
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
            return date;
        }

        protected string GetPreferenceShortDate(DateTime dateTime)
        {
            string date = string.Empty;
            try
            {
                if (!(dateTime != new DateTime()))
                {
                    return date;
                }
                string formatStr = this.GetPreferenceFormatString("DATE_FORMAT");
                if (this.UserInfo.Preference.Time == "Y")
                {
                    formatStr = formatStr + " " + this.GetPreferenceFormatString("TIME_FORMAT");
                }
                date = dateTime.ToString(formatStr, DateTimeFormatInfo.InvariantInfo);
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
            return date;
        }

        protected string GetPreferenceShortDate(string dateTime)
        {
            string date = string.Empty;
            try
            {
                if (string.IsNullOrEmpty(dateTime))
                {
                    return date;
                }
                DateTime tempDate = DateTime.Parse(dateTime);
                if (!(tempDate != new DateTime()))
                {
                    return date;
                }
                string formatStr = this.GetPreferenceFormatString("DATE_FORMAT");
                if (this.UserInfo.Preference.Time == "Y")
                {
                    formatStr = formatStr + " " + this.GetPreferenceFormatString("TIME_FORMAT");
                }
                date = tempDate.ToString(formatStr, DateTimeFormatInfo.InvariantInfo);
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
            return date;
        }

        protected List<string> GetSelectedIDsInGridView(GridView gv, string dataKeyName)
        {
            List<string> ids = new List<string>();
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                if (((CheckBox) gv.Rows[i].FindControl("chbSelect")).Checked)
                {
                    ids.Add(gv.DataKeys[i][dataKeyName].ToString());
                }
            }
            return ids;
        }

        private DataRow[] GetSysCodeDetailDataRows(string codeType)
        {
            DataRow[] drs = null;
            string cacheName = this.UserInfo.CurrentWH + "SysCode";
            if (base.Cache[cacheName] != null)
            {
                DataTable dt = base.Cache[cacheName] as DataTable;
                if ((dt != null) && (dt.Rows.Count > 0))
                {
                    drs = dt.Select("SYS_CODE_TYPE='" + codeType + "'");
                }
                return drs;
            }
            try
            {
                SysCodeDetailQueryEntity sysCodeDetailQuery = new SysCodeDetailQueryEntity {
                    IsActive = " ='Y'",
                    IsGetAll = true,
                    CurrentPage = "",
                    PageSize = "",
                    SortField = "",
                    SortDirection = ""
                };
                DataSet ds = BaseInfoDetailServiceClientProxy.GetInstance().GetDetaiInfolByQueryEntity(sysCodeDetailQuery, "SYS_CODE_DETAIL");
                if (((ds != null) && (ds.Tables.Count > 0)) && (ds.Tables[0].Rows.Count > 0))
                {
                    drs = ds.Tables[0].Select("SYS_CODE_TYPE='" + codeType + "'");
                    base.Cache[cacheName] = ds.Tables[0];
                }
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
            return drs;
        }

        public string GetSysSettingValueByID(string id)
        {
            string value = "N";
            SysSettingInfo sysSetting = BaseInfoServiceClientProxy.GetInstance().GetInfoByID(id, "SYS_SETTING") as SysSettingInfo;
            if (!((sysSetting == null) || string.IsNullOrEmpty(sysSetting.SysSettingID)))
            {
                value = sysSetting.Value;
            }
            return value.ToUpper();
        }

        protected float GetUomQtyByUomList(string uom, List<WMS6.Web.CommonMethodServiceRef.UomList> uomList)
        {
            if ((!string.IsNullOrEmpty(uom) && (uomList != null)) && (uomList.Count > 0))
            {
                for (int i = 0; i < uomList.Count; i++)
                {
                    if (uom == uomList[i].UomID)
                    {
                        return uomList[i].UomQty;
                    }
                }
            }
            return 0f;
        }

        protected string GetValueFromAppSettings(string key)
        {
            string result = "";
            try
            {
                List<GlobalSettingInfo> globalSetting = null;
                if (base.Cache.Get("GLOBAL_SETTING") == null)
                {
                    globalSetting = LoginServiceClientProxy.GetInstance().GetALLGlobalSetting();
                    base.Cache.Add("GLOBAL_SETTING", globalSetting, null, DateTime.Now.AddHours(12.0), TimeSpan.Zero, CacheItemPriority.High, null);
                }
                else
                {
                    globalSetting = base.Cache.Get("GLOBAL_SETTING") as List<GlobalSettingInfo>;
                }
                foreach (GlobalSettingInfo info in globalSetting)
                {
                    if (info.GlobalSettingID.ToUpper() == key.ToUpper())
                    {
                        return info.Value;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex, "从web.config里的appsetting里取值时发生异常,Key：" + key + "!");
            }
            return result;
        }

        private string GetWidthByCssClass(string cssClass)
        {
            return cssClass.Substring(cssClass.LastIndexOf("_") + 1, (cssClass.Length - cssClass.LastIndexOf("_")) - 1);
        }

        protected void HiddenMsgLabel(Label lbl)
        {
            lbl.Visible = false;
        }

        public void InitAnalyticsReportGridview(GridView gv)
        {
            gv.PageSize = ConstUtils.CONST_ANALYTICS_REPORT_LIST_PAGE_COUNT;
        }

        public void InitDetailGridView(string functionID, GridView gv)
        {
            functionID = functionID.ToUpper().Replace("F", "");
            List<WMS6.Web.CommonMethodServiceRef.CustGridviewInfo> custGridviewInfos = CommoneMethodServiceClientProxy.GetInstance().GetCustGridviewInfos(functionID, gv.ID);
            string strPageSize = this.GetValueFromAppSettings("PAGE_DETAIL_COUNT");
            if (!string.IsNullOrEmpty(strPageSize))
            {
                gv.PageSize = int.Parse(strPageSize);
            }
            if ((custGridviewInfos != null) && (custGridviewInfos.Count > 0))
            {
                int i;
                GridView temp = new GridView();
                int totalWidth = 0;
                for (i = 0; i < custGridviewInfos.Count; i++)
                {
                    DataControlField dcFiled = gv.Columns[custGridviewInfos[i].ColumnIndex];
                    dcFiled.HeaderText = custGridviewInfos[i].HeaderText;
                    if (custGridviewInfos[i].Width > 0)
                    {
                        dcFiled.ItemStyle.Width = Unit.Parse(custGridviewInfos[i].Width.ToString());
                    }
                    temp.Columns.Add(dcFiled);
                    totalWidth += int.Parse(dcFiled.ItemStyle.Width.Value.ToString());
                }
                gv.Columns.Clear();
                for (i = 0; i < temp.Columns.Count; i++)
                {
                    gv.Columns.Add(temp.Columns[i]);
                }
                gv.Width = totalWidth;
                if (custGridviewInfos[0].PageSize > 0)
                {
                    gv.PageSize = custGridviewInfos[0].PageSize;
                }
            }
        }

        protected override void InitializeCulture()
        {
            if ((this.UserInfo != null) && (this.Session["UserInfo"] != null))
            {
                string userCulture = this.UserInfo.Preference.Lang;
                if (!string.IsNullOrEmpty(userCulture))
                {
                    if (userCulture.ToUpper() == "EN-*")
                    {
                        userCulture = "en-us";
                    }
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo(userCulture);
                    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(userCulture);
                }
            }
            else if ((this.Page.GetType().FullName != "ASP.login_aspx") && (this.Page.GetType().FullName != "ASP.portal_aspx"))
            {
                if (this.Page.GetType().FullName == "ASP.webform_logo_aspx")
                {
                    base.Response.Write("<script language=javascript>top.location.href='Login.aspx'</script>");
                    base.Response.Write("<script language=javascript>window.location.href='Login.aspx'</script>");
                    base.Response.Write("<script language=javascript>window.parent.close()</script>");
                }
                else
                {
                    base.Response.Write("<script language=javascript>top.location.href='../Login.aspx'</script>");
                    base.Response.Write("<script language=javascript>window.location.href='../Login.aspx'</script>");
                    base.Response.Write("<script language=javascript>window.parent.close()</script>");
                }
            }
        }

        protected void InitIsActiveDDL(DropDownList ddl, int type)
        {
            ddl.Items.Clear();
            switch (type)
            {
                case 0:
                    ddl.Items.Add(new ListItem("-----", ""));
                    ddl.Items.Add(new ListItem("Y", "Y"));
                    ddl.Items.Add(new ListItem("N", "N"));
                    break;

                case 1:
                    ddl.Items.Add(new ListItem("Y", "Y"));
                    ddl.Items.Add(new ListItem("N", "N"));
                    break;

                default:
                    ddl.Items.Add(new ListItem("Y", "Y"));
                    ddl.Items.Add(new ListItem("N", "N"));
                    break;
            }
        }

        protected void InitPage(Page page)
        {
            if ((((this.UserInfo != null) && (this.Session["UserInfo"] != null)) && (this.UserInfo.Preference != null)) && !string.IsNullOrEmpty(this.UserInfo.Preference.Lang))
            {
                if (page.Request.QueryString["ScriptCreated"] == "Created")
                {
                    this.SqlScriptCreatedByPageControlsIsButton(page);
                    this.SqlScriptCreatedByPageGridView(page);
                }
                this.InitUserButtonOperation(page);
                this.GetPageControlXmlElementValue(page);
                if (page.FindControl("hdnDataFormat") != null)
                {
                    string strTime = this.UserInfo.Preference.DateFormat;
                    if (this.UserInfo.Preference.Time == "Y")
                    {
                        strTime = strTime + " " + this.UserInfo.Preference.Time_Format;
                    }
                    (page.FindControl("hdnDataFormat") as HtmlInputHidden).Value = strTime;
                }
                if (this.Session["SearchData"] != null)
                {
                    this.Session["SearchData"] = null;
                }
            }
            else if (this.Page.GetType().FullName != "ASP.login_aspx")
            {
                base.Response.Write("<script language=javascript>top.location.href='../Login.aspx'</script>");
                base.Response.Write("<script language=javascript>window.location.href='../Login.aspx'</script>");
                base.Response.Write("<script language=javascript>window.parent.close()</script>");
            }
        }

        protected void InitQueryDDL(DropDownList ddl, int type)
        {
            if ((((this.UserInfo == null) || (this.Session["UserInfo"] == null)) || (this.UserInfo.Preference == null)) || string.IsNullOrEmpty(this.UserInfo.Preference.Lang))
            {
                this.Session["UserInfo"] = null;
                base.Response.Write("<script language=javascript>top.location.href='../Login.aspx'</script>");
                base.Response.Write("<script language=javascript>window.location.href='../Login.aspx'</script>");
                base.Response.Write("<script language=javascript>window.parent.close()</script>");
            }
            else
            {
                DataTable listItems = null;
                switch (type)
                {
                    case 0:
                        if (!(this.UserInfo.Preference.Lang.ToUpper() == "ZH-CN"))
                        {
                            if (this.UserInfo.Preference.Lang.ToUpper() == "EN-*")
                            {
                                if (base.Cache["StringOper_EN"] == null)
                                {
                                    listItems = DDLQueryDataSource.GetInstance().StringSign4DDLByDT();
                                    base.Cache.Add("StringOper_EN", listItems, null, DateTime.Now.AddMinutes(20.0), TimeSpan.Zero, CacheItemPriority.High, null);
                                }
                                else
                                {
                                    listItems = (DataTable) base.Cache["StringOper_EN"];
                                }
                            }
                            else if (this.UserInfo.Preference.Lang.ToUpper() == "ZH-TW")
                            {
                                if (base.Cache["StringOper_TW"] == null)
                                {
                                    listItems = DDLQueryDataSource.GetInstance().StringSign4DDLByDT();
                                    base.Cache.Add("StringOper_TW", listItems, null, DateTime.Now.AddMinutes(20.0), TimeSpan.Zero, CacheItemPriority.High, null);
                                }
                                else
                                {
                                    listItems = (DataTable) base.Cache["StringOper_TW"];
                                }
                            }
                            else if (base.Cache["StringOper_CN"] == null)
                            {
                                listItems = DDLQueryDataSource.GetInstance().StringSign4DDLByDT();
                                base.Cache.Add("StringOper_CN", listItems, null, DateTime.Now.AddMinutes(20.0), TimeSpan.Zero, CacheItemPriority.High, null);
                            }
                            else
                            {
                                listItems = (DataTable) base.Cache["StringOper_CN"];
                            }
                            break;
                        }
                        if (base.Cache["StringOper_CN"] != null)
                        {
                            listItems = (DataTable) base.Cache["StringOper_CN"];
                            break;
                        }
                        listItems = DDLQueryDataSource.GetInstance().StringSign4DDLByDT();
                        base.Cache.Add("StringOper_CN", listItems, null, DateTime.Now.AddMinutes(20.0), TimeSpan.Zero, CacheItemPriority.High, null);
                        break;

                    case 1:
                        if (!(this.UserInfo.Preference.Lang.ToUpper() == "ZH-CN"))
                        {
                            if (this.UserInfo.Preference.Lang.ToUpper() == "EN-*")
                            {
                                if (base.Cache["DateTimeOper_EN"] == null)
                                {
                                    listItems = DDLQueryDataSource.GetInstance().DateTimeSign4DDLByDT();
                                    base.Cache.Add("DateTimeOper_EN", listItems, null, DateTime.Now.AddMinutes(20.0), TimeSpan.Zero, CacheItemPriority.High, null);
                                }
                                else
                                {
                                    listItems = (DataTable) base.Cache["DateTimeOper_EN"];
                                }
                            }
                            else if (this.UserInfo.Preference.Lang.ToUpper() == "ZH-TW")
                            {
                                if (base.Cache["DateTimeOper_TW"] == null)
                                {
                                    listItems = DDLQueryDataSource.GetInstance().DateTimeSign4DDLByDT();
                                    base.Cache.Add("DateTimeOper_TW", listItems, null, DateTime.Now.AddMinutes(20.0), TimeSpan.Zero, CacheItemPriority.High, null);
                                }
                                else
                                {
                                    listItems = (DataTable) base.Cache["DateTimeOper_TW"];
                                }
                            }
                            else if (base.Cache["DateTimeOper_CN"] == null)
                            {
                                listItems = DDLQueryDataSource.GetInstance().DateTimeSign4DDLByDT();
                                base.Cache.Add("DateTimeOper_CN", listItems, null, DateTime.Now.AddMinutes(20.0), TimeSpan.Zero, CacheItemPriority.High, null);
                            }
                            else
                            {
                                listItems = (DataTable) base.Cache["DateTimeOper_CN"];
                            }
                            break;
                        }
                        if (base.Cache["DateTimeOper_CN"] != null)
                        {
                            listItems = (DataTable) base.Cache["DateTimeOper_CN"];
                            break;
                        }
                        listItems = DDLQueryDataSource.GetInstance().DateTimeSign4DDLByDT();
                        base.Cache.Add("DateTimeOper_CN", listItems, null, DateTime.Now.AddMinutes(20.0), TimeSpan.Zero, CacheItemPriority.High, null);
                        break;

                    case 2:
                        if (base.Cache["EqualDLLByDT"] != null)
                        {
                            listItems = (DataTable) base.Cache["EqualDLLByDT"];
                            break;
                        }
                        listItems = DDLQueryDataSource.GetInstance().EqualDLLByDT();
                        base.Cache.Add("EqualDLLByDT", listItems, null, DateTime.Now.AddMinutes(20.0), TimeSpan.Zero, CacheItemPriority.High, null);
                        break;
                }
                if ((listItems != null) && (listItems.Rows.Count > 0))
                {
                    ddl.DataSource = listItems;
                    ddl.DataTextField = "Text";
                    ddl.DataValueField = "Value";
                    ddl.DataBind();
                }
            }
        }

        protected void InitUserButtonOperation(Page page)
        {
            if (string.IsNullOrEmpty(page.Request.QueryString["action"]))
            {
                string userID = this.UserInfo.UserID;
                string functionID = page.Form.Name.ToUpper().Replace("F", "");
                List<string> operations = RoleFunctionServiceClientProxy.GetInstance().GetOperationByUserIDAndFunctionID(userID, functionID);
                if ((operations != null) && (operations.Count > 0))
                {
                    for (int i = 0; i < operations.Count; i++)
                    {
                        if (this.Page.FindControl(operations[i]) is Button)
                        {
                            ((Button) this.Page.FindControl(operations[i])).Enabled = true;
                        }
                        else if (this.Page.FindControl(operations[i]) is LinkButton)
                        {
                            ((LinkButton) this.Page.FindControl(operations[i])).Width = 0x69;
                            ((HtmlTableCell) this.Page.FindControl("td" + operations[i])).Visible = true;
                        }
                    }
                }
            }
            else
            {
                foreach (Control ctrl in page.Form.Controls)
                {
                    if (ctrl is Button)
                    {
                        ((Button) ctrl).Enabled = true;
                    }
                }
            }
        }

        public bool SandMail(string EmailCode, List<string> parameter)
        {
            EmailSettingInfo emailSettingInfo = BaseInfoServiceClientProxy.GetInstance().GetInfoByID(EmailCode, "EMAIL_SETTING") as EmailSettingInfo;
            bool result = false;
            if (emailSettingInfo == null)
            {
                return result;
            }
            if (!(emailSettingInfo.IsActive == "Y"))
            {
                return result;
            }
            string strBody = string.Format(emailSettingInfo.Content, (object[]) parameter.ToArray());
            try
            {
                SmtpClient smtp = new SmtpClient();
                MailMessage mail = new MailMessage();
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Host = emailSettingInfo.Smtp;
                smtp.Credentials = new NetworkCredential(emailSettingInfo.EmailAccount, emailSettingInfo.EmalPwd);
                mail.From = new MailAddress(emailSettingInfo.EmailAccount);
                mail.To.Add(emailSettingInfo.Addressee);
                if (!string.IsNullOrEmpty(emailSettingInfo.CarbonCopy))
                {
                    mail.CC.Add(emailSettingInfo.CarbonCopy);
                }
                mail.Subject = emailSettingInfo.Description;
                mail.Body = strBody;
                mail.BodyEncoding = Encoding.UTF8;
                mail.IsBodyHtml = emailSettingInfo.IsHtml == "Y";
                mail.Priority = MailPriority.Normal;
                smtp.Send(mail);
                return true;
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
                return false;
            }
        }

        public bool SandMail(string EmailCode, List<string> parameter, string UserMail)
        {
            EmailSettingInfo emailSettingInfo = BaseInfoServiceClientProxy.GetInstance().GetInfoByID(EmailCode, "EMAIL_SETTING") as EmailSettingInfo;
            bool result = false;
            if (emailSettingInfo == null)
            {
                return result;
            }
            if (!(emailSettingInfo.IsActive == "Y"))
            {
                return result;
            }
            string strBody = string.Format(emailSettingInfo.Content, (object[]) parameter.ToArray());
            try
            {
                string strAdd = emailSettingInfo.Addressee + "," + UserMail;
                if (string.IsNullOrEmpty(strAdd))
                {
                    return result;
                }
                SmtpClient smtp = new SmtpClient();
                MailMessage mail = new MailMessage();
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Host = emailSettingInfo.Smtp;
                smtp.Credentials = new NetworkCredential(emailSettingInfo.EmailAccount, emailSettingInfo.EmalPwd);
                mail.From = new MailAddress(emailSettingInfo.EmailAccount);
                mail.To.Add(strAdd);
                if (!string.IsNullOrEmpty(emailSettingInfo.CarbonCopy))
                {
                    mail.CC.Add(emailSettingInfo.CarbonCopy);
                }
                mail.Subject = emailSettingInfo.Description;
                mail.Body = strBody;
                mail.BodyEncoding = Encoding.UTF8;
                mail.IsBodyHtml = emailSettingInfo.IsHtml == "Y";
                mail.Priority = MailPriority.Normal;
                smtp.Send(mail);
                return true;
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
                return false;
            }
        }

        public void SaveSelectedInGridView(GridView gv, string dataKeyName)
        {
            List<string> ids = this.DataGridViewState as List<string>;
            if (ids == null)
            {
                ids = new List<string>();
            }
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                if (((CheckBox) gv.Rows[i].FindControl("chbSelect")).Checked)
                {
                    if (!ids.Contains(gv.DataKeys[i][dataKeyName].ToString()))
                    {
                        ids.Add(gv.DataKeys[i][dataKeyName].ToString());
                    }
                }
                else
                {
                    ids.Remove(gv.DataKeys[i][dataKeyName].ToString());
                }
            }
            this.DataGridViewState = ids;
        }

        public void SetDefaultCustomer(TextBox txtbox)
        {
            if (!((((this.UserInfo == null) || (this.Session["UserInfo"] == null)) || (this.UserInfo.Preference == null)) || string.IsNullOrEmpty(this.UserInfo.Preference.Lang)))
            {
                txtbox.Text = this.UserInfo.CustomerID;
            }
            else if (this.Page.GetType().FullName != "ASP.login_aspx")
            {
                base.Response.Write("<script language=javascript>top.location.href='../Login.aspx'</script>");
                base.Response.Write("<script language=javascript>window.location.href='../Login.aspx'</script>");
                base.Response.Write("<script language=javascript>window.parent.close()</script>");
            }
        }

        public void SetDefaultOwner(TextBox txtbox)
        {
            if (!((((this.UserInfo == null) || (this.Session["UserInfo"] == null)) || (this.UserInfo.Preference == null)) || string.IsNullOrEmpty(this.UserInfo.Preference.Lang)))
            {
                txtbox.Text = this.UserInfo.OwnerID;
            }
            else if (this.Page.GetType().FullName != "ASP.login_aspx")
            {
                base.Response.Write("<script language=javascript>top.location.href='../Login.aspx'</script>");
                base.Response.Write("<script language=javascript>window.location.href='../Login.aspx'</script>");
                base.Response.Write("<script language=javascript>window.parent.close()</script>");
            }
        }

        public void SetGridViewCheckInDataGridViewState(string index, CheckBox ckb)
        {
            List<string> myList = this.DataGridViewState as List<string>;
            if (((myList != null) && (myList.Count > 0)) && myList.Contains(index))
            {
                CheckBox myCheckBox = ckb;
                myCheckBox.Checked = true;
            }
        }

        public void SetGridViewLongTextLabel(Label label)
        {
            if (label != null)
            {
                label.ToolTip = label.Text;
                label.Text = this.SubString4SetLongText(label.Text, 14);
            }
        }

        public void SetQueryParams(string value, TextBox txt, DropDownList ddl)
        {
            try
            {
                if (!string.IsNullOrEmpty(value))
                {
                    value = value.TrimStart(new char[0]).TrimEnd(new char[0]);
                    if (value.StartsWith("LIKE '%") && value.EndsWith("%'"))
                    {
                        txt.Text = value.Substring(value.IndexOf('%') + 1, (value.LastIndexOf('%') - value.IndexOf('%')) - 1);
                        ddl.SelectedValue = "Contains";
                    }
                    else if (value.StartsWith("NOT LIKE '%") && value.EndsWith("%'"))
                    {
                        txt.Text = value.Substring(value.IndexOf('%') + 1, (value.LastIndexOf('%') - value.IndexOf('%')) - 1);
                        ddl.SelectedValue = "Not Contains";
                    }
                    else if (value.StartsWith("LIKE '") && value.EndsWith("%'"))
                    {
                        txt.Text = value.Substring(value.IndexOf('\'') + 1, (value.LastIndexOf('%') - value.IndexOf('\'')) - 1);
                        ddl.SelectedValue = "Begins With";
                    }
                    else if (value.StartsWith("LIKE '%") && value.EndsWith("'"))
                    {
                        txt.Text = value.Substring(value.IndexOf('%') + 1, (value.LastIndexOf('\'') - value.IndexOf('%')) - 1);
                        ddl.SelectedValue = "Ends With";
                    }
                    else if (value.StartsWith("IN ( '") && value.EndsWith("' )"))
                    {
                        txt.Text = value.Substring(value.IndexOf('\'') + 1, (value.LastIndexOf(')') - value.IndexOf('\'')) - 3);
                        ddl.SelectedValue = "One Of";
                    }
                    else if (value.StartsWith("NOT IN ( '") && value.EndsWith("' )"))
                    {
                        txt.Text = value.Substring(value.IndexOf('\'') + 1, (value.LastIndexOf(')') - value.IndexOf('\'')) - 3);
                        ddl.SelectedValue = "Not One Of";
                    }
                    else if (value.StartsWith("= '") && value.EndsWith("'"))
                    {
                        txt.Text = value.Substring(value.IndexOf('\'') + 1, (value.LastIndexOf('\'') - value.IndexOf('\'')) - 1);
                        ddl.SelectedValue = "Same As";
                    }
                    else if (value.StartsWith("!= '") && value.EndsWith("'"))
                    {
                        txt.Text = value.Substring(value.IndexOf('\'') + 1, (value.LastIndexOf('\'') - value.IndexOf('\'')) - 1);
                        ddl.SelectedValue = "Not Same As";
                    }
                }
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
        }

        protected void ShowMsgLabel(Label lbl, string message)
        {
            lbl.Visible = true;
            lbl.Text = message;
        }

        public void SqlScriptCreatedByPageControlsIsButton(Page page)
        {
            string StrFunctionID = page.Request.QueryString["FunctionID"];
            if (string.IsNullOrEmpty(StrFunctionID))
            {
                StrFunctionID = page.Form.Name;
            }
            StrFunctionID = StrFunctionID.Replace("F", "");
            string StrUserName = this.UserInfo.UserName;
            string StrPageName = page.GetType().Name.Split(new char[] { '_' })[1].ToUpper();
            StringBuilder strSql = new StringBuilder();
            strSql.Append("/*-----------------------------------------------------");
            strSql.AppendLine();
            strSql.AppendLine();
            strSql.Append(" Copyright (C) 2011-2015 上海微果软件版权所有。  ");
            strSql.AppendLine();
            strSql.AppendLine();
            strSql.AppendFormat(" 创建人：    {0}", StrUserName.ToUpper());
            strSql.AppendLine();
            strSql.AppendLine();
            strSql.AppendFormat(" 创建日期：  {0}", DateTime.Now.ToString("yyyy-MM-dd"));
            strSql.AppendLine();
            strSql.AppendLine();
            strSql.AppendFormat(" 脚本名称：  {0}页面按钮插入脚本", StrPageName);
            strSql.AppendLine();
            strSql.AppendLine();
            strSql.Append("------------------------------------------------------*/");
            strSql.AppendLine();
            strSql.AppendLine();
            strSql.Append("    USE POWERWMS6 ");
            strSql.AppendLine();
            strSql.AppendLine();
            strSql.AppendFormat(" DELETE FROM SYSADM.OPERATION_LIST WHERE FUNCTION_ID = '{0}'", StrFunctionID);
            strSql.AppendLine();
            try
            {
                foreach (Control info in page.Form.Controls)
                {
                    if (info is Button)
                    {
                        strSql.AppendLine();
                        strSql.Append(" INSERT INTO SYSADM.OPERATION_LIST(FUNCTION_ID, BUTTON_NAME, REMARK, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE )");
                        strSql.AppendFormat("VALUES('{0}','{1}','{2}','{3}',GETDATE(),'{3}',GETDATE()) ", new object[] { StrFunctionID, info.ID, ((Button) page.FindControl(info.ID)).Text, StrUserName });
                        strSql.AppendLine();
                    }
                    if (info is LinkButton)
                    {
                        strSql.AppendLine();
                        strSql.Append(" INSERT INTO SYSADM.OPERATION_LIST(FUNCTION_ID, BUTTON_NAME, REMARK, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE )");
                        strSql.AppendFormat("VALUES('{0}','{1}','{2}','{3}',GETDATE(),'{3}',GETDATE()) ", new object[] { StrFunctionID, info.ID, ((LinkButton) page.FindControl(info.ID)).Text, StrUserName });
                        strSql.AppendLine();
                    }
                }
                System.IO.File.WriteAllText("D://SqlScript(" + StrPageName + ").sql", strSql.ToString(), Encoding.UTF8);
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
        }

        public void SqlScriptCreatedByPageGridView(Page page)
        {
            string StrFunctionID = page.Request.QueryString["FunctionID"];
            if (string.IsNullOrEmpty(StrFunctionID))
            {
                StrFunctionID = page.Form.Name;
            }
            StrFunctionID = StrFunctionID.Replace("F", "");
            string StrUserName = this.UserInfo.UserName;
            string StrPageName = page.GetType().Name.Split(new char[] { '_' })[1].ToUpper();
            foreach (Control info in page.Form.Controls)
            {
                if (info is GridView)
                {
                    this.CreateInitGridviewSQL(StrFunctionID, info as GridView);
                }
            }
        }

        public string SubString4SetLongText(string text, int textLength)
        {
            Regex reg = new Regex("^[A-Za-z0-9]+$");
            if (reg.IsMatch(text))
            {
                textLength = 20;
            }
            if (text.Length <= textLength)
            {
                return text;
            }
            return (text.Substring(0, textLength) + "...");
        }

        protected WMS6.Web.LoginServiceRef.UserMstInfo TurnUserInfo(WMS6.Web.BaseInfoServiceRef.UserMstInfo userInfo)
        {
            return new WMS6.Web.LoginServiceRef.UserMstInfo { 
                Address = userInfo.Address, City = userInfo.City, Country = userInfo.Country, CountryCode = userInfo.CountryCode, CreatedBy = userInfo.CreatedBy, CreatedDate = userInfo.CreatedDate, CurrentWH = userInfo.CurrentWH, Department = userInfo.Department, Email = userInfo.Email, ExpireDate = userInfo.ExpireDate, Fax = userInfo.Fax, IsActive = userInfo.IsActive, IsDomainUser = userInfo.IsDomainUser, IsGlobal = userInfo.IsGlobal, IsLocked = userInfo.IsLocked, IsLogin = userInfo.IsLogin, 
                LockDate = userInfo.LockDate, Mobile = userInfo.Mobile, Passwd = userInfo.Passwd, PasswdDate = userInfo.PasswdDate, PerfLanguage = userInfo.PerfLanguage, PerfStyle = userInfo.PerfStyle, Phone = userInfo.Phone, RowID = userInfo.RowID, State = userInfo.State, Status = userInfo.Status, SystemCreated = userInfo.SystemCreated, Ts = userInfo.Ts, UpdatedBy = userInfo.UpdatedBy, UpdatedDate = userInfo.UpdatedDate, UserID = userInfo.UserID, UserName = userInfo.UserName, 
                WhDbDesc = userInfo.WhDbDesc, Zip = userInfo.Zip, IsWhUser = userInfo.IsWhUser
             };
        }

        protected WMS6.Web.BaseInfoServiceRef.UserMstInfo TurnUserInfo(WMS6.Web.LoginServiceRef.UserMstInfo userInfo)
        {
            return new WMS6.Web.BaseInfoServiceRef.UserMstInfo { 
                Address = userInfo.Address, City = userInfo.City, Country = userInfo.Country, CountryCode = userInfo.CountryCode, CreatedBy = userInfo.CreatedBy, CreatedDate = userInfo.CreatedDate, CurrentWH = userInfo.CurrentWH, Department = userInfo.Department, Email = userInfo.Email, ExpireDate = userInfo.ExpireDate, Fax = userInfo.Fax, IsActive = userInfo.IsActive, IsDomainUser = userInfo.IsDomainUser, IsGlobal = userInfo.IsGlobal, IsLocked = userInfo.IsLocked, IsLogin = userInfo.IsLogin, 
                LockDate = userInfo.LockDate, Mobile = userInfo.Mobile, Passwd = userInfo.Passwd, PasswdDate = userInfo.PasswdDate, PerfLanguage = userInfo.PerfLanguage, PerfStyle = userInfo.PerfStyle, Phone = userInfo.Phone, RowID = userInfo.RowID, State = userInfo.State, Status = userInfo.Status, SystemCreated = userInfo.SystemCreated, Ts = userInfo.Ts, UpdatedBy = userInfo.UpdatedBy, UpdatedDate = userInfo.UpdatedDate, UserID = userInfo.UserID, UserName = userInfo.UserName, 
                WhDbDesc = userInfo.WhDbDesc, Zip = userInfo.Zip, IsWhUser = userInfo.IsWhUser
             };
        }

        protected string UrlEncode(string paras)
        {
            return base.Server.UrlEncode(paras);
        }

        protected string UrlReplace(string paras)
        {
            return paras.Replace("'", "’").Replace(",", "，").Replace(";", "；");
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
        }

        public void XmlCreatedByPageControls(string Name, HtmlForm form)
        {
            StringBuilder strXml = new StringBuilder();
            strXml.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            strXml.AppendLine("<PageConfig>");
            try
            {
                foreach (Control info in form.Controls)
                {
                    if (info is TextBox)
                    {
                        string strsubControl = info.ID.Replace("txt", "img");
                        strXml.AppendLine("<PageControl ControlName=\"" + info.ID + "\" Enable=\"FALSE\" SubControl=\"" + strsubControl + "\" ></PageControl>");
                    }
                    if (info is DropDownList)
                    {
                        strXml.AppendLine("<PageControl ControlName=\"" + info.ID + "\" Enable=\"FALSE\" SubControl=\"\" ></PageControl>");
                    }
                    if (info is CheckBox)
                    {
                        strXml.AppendLine("<PageControl ControlName=\"" + info.ID + "\" Enable=\"FALSE\" SubControl=\"\" ></PageControl>");
                    }
                    if (info is Button)
                    {
                        strXml.AppendLine("<PageControl ControlName=\"" + info.ID + "\" Enable=\"FALSE\" SubControl=\"\" ></PageControl>");
                    }
                }
                strXml.AppendLine("</PageConfig>");
                System.IO.File.WriteAllText(base.Server.MapPath("../PageConfig") + @"\" + Name + ".xml", strXml.ToString(), Encoding.UTF8);
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex);
            }
        }

        protected object DataEntityViewState
        {
            get
            {
                return this.ViewState["DataEntityViewState"];
            }
            set
            {
                this.ViewState["DataEntityViewState"] = value;
            }
        }

        protected object DataGridViewState
        {
            get
            {
                return this.ViewState["DataGridViewState"];
            }
            set
            {
                this.ViewState["DataGridViewState"] = value;
            }
        }

        protected SortDirection GridViewSortDirection
        {
            get
            {
                if (this.ViewState["sortDirection"] == null)
                {
                    this.ViewState["sortDirection"] = SortDirection.Ascending;
                }
                return (SortDirection) this.ViewState["sortDirection"];
            }
            set
            {
                this.ViewState["sortDirection"] = value;
            }
        }

        protected object PageDetailQueryEntitySession
        {
            get
            {
                return this.Session["PageDetailQueryEntitySession"];
            }
            set
            {
                this.Session["PageDetailQueryEntitySession"] = value;
            }
        }

        protected object PageQueryEntitySession
        {
            get
            {
                return this.Session["PageQueryEntitySession"];
            }
            set
            {
                this.Session["PageQueryEntitySession"] = value;
            }
        }

        protected object PageQueryEntityViewState
        {
            get
            {
                return this.ViewState["PageQueryEntityViewState"];
            }
            set
            {
                this.ViewState["PageQueryEntityViewState"] = value;
            }
        }

        protected WMS6.Web.LoginServiceRef.UserMstInfo UserInfo
        {
            get
            {
                return (this.Session["UserInfo"] as WMS6.Web.LoginServiceRef.UserMstInfo);
            }
            set
            {
                this.Session["UserInfo"] = value;
            }
        }

        protected PreferenceProfileInfo UserPreferenceInfo
        {
            get
            {
                return (this.Session["UserPreferenceInfo"] as PreferenceProfileInfo);
            }
            set
            {
                this.Session["UserPreferenceInfo"] = value;
            }
        }
    }
}

